#include <iostream>
#include <thread>
#include <future>
#include <memory>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <vector>

class threadpool
{
public:
    using Functor = std::function<void(void)>;
    threadpool(int threadcount = 3)
        : _stop(false)
    {
        for(int i = 0; i < threadcount; i++)
            _threads.emplace_back(&threadpool::entry, this);
    }
    ~threadpool()
    {
        stop();
    }

    //将函数和参数封装成异步任务
    template<typename F, typename ...Args>
    auto push(F&& func, Args&& ...args) -> std::future<decltype(func(args...))>
    {
        //封装一个packaged_task对象，智能指针指向这个对象
        using return_type = decltype(func(args...));
        auto bound_func = std::bind(std::forward<F>(func), std::forward<Args>(args)...);
        auto ptask = std::make_shared<std::packaged_task<return_type()>>(bound_func);
        std::future<return_type> fu = ptask->get_future();  //建立关联关系

        {
            std::unique_lock<std::mutex> lock(_mutex);
            _tasks.emplace_back([ptask](){(*ptask)();});
            _cond.notify_one();
        }
        return fu;
    }

    void stop()
    {
        _stop = true;
        _cond.notify_all();
        for(auto &thread : _threads)
        {
            thread.join();
        }
    }
private:
    void entry()
    {
        while(!_stop)
        {
            std::vector<Functor> tmp_tasks;
            {
                std::unique_lock<std::mutex> lock(_mutex);
                _cond.wait(lock, [this](){return _stop || !_tasks.empty();});
                tmp_tasks.swap(_tasks);//难怪，等待完毕需要一把锁，所以才可以起到保护作用
            }
            for(auto& task : tmp_tasks)
                task();
        }
    }
private:
    std::atomic<bool> _stop;
    std::vector<Functor> _tasks;
    std::mutex _mutex;// 放在线程池前面防止未初始化
    std::condition_variable _cond; // 放在线程池前面防止未初始化
    std::vector<std::thread> _threads;
}; 
int Add(int num1, int num2)
{
    return num1 + num2;
}
int main()
{
    threadpool tp;
    for(int i = 0; i < 10; i++)
    {
        auto fu = tp.push(Add, 10, i);
        std::cout << fu.get() << std::endl;
    }
    return 0;
}